package hilos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import com.gio.lib.conexion.*;
import com.bd.dal;
import com.encuestas.preferencias;
import com.encuestas.utilidades;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class backup extends AsyncTask<String, Void, Integer> {

	public interface CompletionListener {
		void onBackupComplete();
		void onRestoreComplete();
		void onBackupSyncComplete();
		void onError(int errorCode);
	}

	private Context mContext;
	dal datos;
	preferencias pref;
	private CompletionListener listener;
	private static final String DB_NAME = "proyectos.db";
	public static final int BACKUP_SUCCESS = 1;
	public static final int RESTORE_SUCCESS = 2;
	public static final int RESTORE_SYNC_SUCESS = 8;
	public static final int BACKUP_ERROR = 3;
	public static final int RESTORE_NOFILEERROR = 4;
	public static final int NoSDIN = 5;
	public static final int NoConex = 6;
	public static final int NoSync = 7;

	ProgressDialog progreso;
	private static String DB_PATH = "";
	public static final String COMMAND_BACKUP = "backupDatabase";
	public static final String COMMAND_RESTORE = "restoreDatabase";
	public static final String COMMAND_SYNC = "restoreDatabaseserver";

	public backup(Context contesto)
	{
		super();
		mContext=contesto;
		datos = new dal(mContext);
		pref = new preferencias(mContext);
		StringBuilder stringbuilder = new StringBuilder("/data/");
		String s = mContext.getApplicationContext().getPackageName();
		DB_PATH = stringbuilder.append(s).append("/databases/").toString();
	}


	public void setCompletionListener(CompletionListener aListener) {
		listener = aListener; 
	}



	@Override
	protected void onPreExecute() {

		
		this.progreso = new ProgressDialog(this.mContext);
	    this.progreso.setMessage("Sincronizando con el servidor, tenga paciencia");
	    this.progreso.setIndeterminate(false);
	    this.progreso.setMax(100);
	    this.progreso.setProgressStyle(1);
	    this.progreso.setCancelable(true);
	    this.progreso.show();


	}


	protected Integer doInBackground(String... params) {

		String[]directorios = utilidades.getStorageDirectories();
		//File sdd = new File(directorios[1]);
		// configuracio tableta
		//File sdd = new File("mnt/sdcard2");
		
		//configuracion telefono
		File sd = Environment.getExternalStorageDirectory();
		File data = Environment.getDataDirectory();

		try {

			if (sd.canWrite()) {

				File actuabase = new File(data, DB_PATH + DB_NAME);
				File carpeta = new File(sd + "/proyectos");
				File backup = new File(carpeta, DB_NAME);
				if (!carpeta.exists()) {
					carpeta.mkdir();

				}


				String comando = params[0];
				if(comando.equals(COMMAND_BACKUP))
				{

					//backup.this.progreso.setMessage("Exportando base de datos..");

					if (actuabase.exists()) {

						try {

							FileChannel src = new FileInputStream(actuabase)
							.getChannel();
							FileChannel out = new FileOutputStream(backup)
							.getChannel();
							out.transferFrom(src, 0, src.size());
							src.close();
							out.close();
							return BACKUP_SUCCESS;

						} catch (FileNotFoundException e) {
							
							
							return BACKUP_ERROR;

						} catch (IOException e) {
							return BACKUP_ERROR;
						}

					}



				}

				else if(comando.equals(COMMAND_RESTORE))
				{

					if(!backup.exists())
					{

						return RESTORE_NOFILEERROR;
					}


					actuabase.createNewFile();

					try {

						FileChannel src = new FileInputStream(backup).getChannel();
						FileChannel out = new FileOutputStream(actuabase).getChannel();
						out.transferFrom(src, 0, src.size());
						src.close();
						out.close();
						
						return RESTORE_SUCCESS;

					} catch (FileNotFoundException e) {
						Log.e("ERROR DE BACKUP", e.getMessage());
						return BACKUP_ERROR;

					} catch (IOException e) {
						Log.e("ERROR DE BACKUP", e.getMessage());
						return BACKUP_ERROR;
					}





				}
				else if(comando.equals(COMMAND_SYNC))
				{
					
			
					long tamano= datos.sizeBD();
					if (tamano==0)
					{
						return NoSync;

					}

					
					List<String>respaldoupload= datos.sqljsonSyncList(pref.getIdProyecto(), "proyectos");
					 int i = 0;
			            int j = 0;
			            int k = respaldoupload.size();
		
					int bien=0, mal=0;
					
					int longitud= respaldoupload.size();
					for(int p= 0;p< respaldoupload.size(); p++)
					{

						String Jsone = "[" + respaldoupload.get(p) + "]";
					

						try{	
							HttpParams params1 = new BasicHttpParams();
							params1.setParameter("MAX_TOTAL_CONNECTIONS", 100);
							HttpConnectionParams.setConnectionTimeout(params1, 60000);
							HttpConnectionParams.setSoTimeout(params1, 60000);
							HttpClient cliente = new DefaultHttpClient(params1);
							//este es el envia para el servidor en produccion
							///HttpPost post = new HttpPost(this.pref.getServervidor() + "guardarmovilencuestas.php");
							HttpPost post = new HttpPost(this.pref.getServervidor() + "guardarmovilfast.php");
							List<NameValuePair> l = new ArrayList<NameValuePair>();
							l.add(new BasicNameValuePair("jsonw", Jsone));
							Jsone="";

							UrlEncodedFormEntity datos = new UrlEncodedFormEntity(l);

							post.setEntity(datos);
							if(!sync.chequeaConexionInternet(backup.this.mContext))
							{

								return NoConex;

							}

							String resultado;
							HttpResponse respuesta=	cliente.execute(post);


							HttpEntity  entiti = respuesta.getEntity();
							if (entiti!= null)
							{
								resultado=utilidades.ObtenerStRes(entiti.getContent());
								cliente.getConnectionManager().shutdown();
								if(resultado.startsWith("0"))
								{
									
									j++;
									 Log.e("error al sioncronizar ALERTA","" + i);
									//return NoSync;

								}
								else if(resultado.startsWith("1"))
								{
									 i++;
					                    Log.i("encuesta enviada numero ",""+ i);
					                    this.progreso.setProgress(i * 100 / k);
									
									//return	RESTORE_SYNC_SUCESS;

								}


							}
							
							
							else 
							{

								return NoSync;
							}



							// este es el original
							/*long tamano= datos.sizeBD();
					if (tamano==0)
					{
						return NoSync;

					}

					String Jsone = "[" + datos.sqljsonSyncList("1", "proyectos") + "]";
					 int longitud= Jsone.length();

			try{	
					HttpParams params1 = new BasicHttpParams();
					params1.setParameter("MAX_TOTAL_CONNECTIONS", 100);
					HttpConnectionParams.setConnectionTimeout(params1, 60000);
					HttpConnectionParams.setSoTimeout(params1, 60000);
					HttpClient cliente = new DefaultHttpClient(params1);
					//este es el envia para el servidor en produccion
					///HttpPost post = new HttpPost(this.pref.getServervidor() + "guardarmovilencuestas.php");
					HttpPost post = new HttpPost(this.pref.getServervidor() + "syncroprueba.php");
					List<NameValuePair> l = new ArrayList<NameValuePair>();
					l.add(new BasicNameValuePair("jsonw", Jsone));

					UrlEncodedFormEntity datos = new UrlEncodedFormEntity(l);

					post.setEntity(datos);
					if(!sync.chequeaConexionInternet(backup.this.mContext))
					{

						return NoConex;

					}

					String resultado;
					HttpResponse respuesta=	cliente.execute(post);


					HttpEntity  entiti = respuesta.getEntity();
					if (entiti!= null)
					{
					resultado=utilidades.ObtenerStRes(entiti.getContent());
					cliente.getConnectionManager().shutdown();
					if(resultado.startsWith("0"))
					{
						return NoSync;

					}
					else if(resultado.startsWith("1"))
					{
					return	RESTORE_SYNC_SUCESS;

					}


					}
					else 
					{

						return NoSync;
					}*/






						} catch (ClientProtocolException e) {


							return NoConex;

						} catch (IOException e) {

							return NoConex;



						}


					}
					
					if(i==longitud)
					{
						
						return	RESTORE_SYNC_SUCESS;
					}
					else
					{
						
						return	NoSync;
						
					}
					
					
					
					
					
				}
					

					else
					{

						return BACKUP_ERROR;	
					}




				}

				else {

					return NoSDIN;

				}

			}

			catch (Exception e) {

				Log.e("error de escritura en almacenamiento externo",
						e.getMessage());
				return BACKUP_ERROR;	

			}
			return BACKUP_ERROR;
		}


		protected void onPostExecute(Integer result) {

			if(progreso.isShowing())
			{

				progreso.dismiss();

			}


			switch (result) {
			case BACKUP_SUCCESS:

				if(listener != null)
				{
					listener.onBackupComplete();

				}

				break;

			case RESTORE_SUCCESS:

				if(listener != null)
				{
					listener.onRestoreComplete();

				}

				break;

			case RESTORE_SYNC_SUCESS:

				if(listener != null)
				{
					listener.onBackupSyncComplete();

				}

				break;		


			case NoSync:

				if(listener != null)
				{
					listener.onError(NoSync);

				}

				break;


			case NoConex:

				if(listener != null)
				{
					listener.onError(NoConex);

				}

				break;

			case RESTORE_NOFILEERROR:

				if(listener != null)
				{
					listener.onError(RESTORE_NOFILEERROR);

				}

				break;

			case NoSDIN:

				if(listener != null)
				{
					listener.onError(NoSDIN);

				}

				break;	


			default:
				if(listener != null)
				{
					listener.onError(BACKUP_ERROR);

				}
				break;
			}

		}



	}
